package com.ileaf.chromosphere;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Lianlb
 * @since 2019-11-21 19:45
 */
public class ThreadPoolUtil {

    private static int count = 0;

    public static void main(String[] args) {
//        Task task = new Task("t0");
        ThreadPoolExecutor exe1 = new ThreadPoolExecutor(4, 8, 5000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(50), new HrThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
//        exe1.shutdown();
//        ScheduledThreadPoolExecutor exe2 = new ScheduledThreadPoolExecutor(4, new HrThreadFactory());
//        exe2.scheduleAtFixedRate(new Task("t1"), 1, 2, TimeUnit.SECONDS);
//        exe2.scheduleWithFixedDelay(new Task("t2"), 1, 2, TimeUnit.SECONDS);
        for (int i = 0; i < 100; i++) {
            exe1.execute(new Task("t" + (i + 1)));
        }
        exe1.shutdown();
        while (true) {
            if (exe1.isTerminated()) {
                System.out.println("Result：" + count);
                return;
            }
        }
    }

    static class Task implements Runnable {

        private String name;

        public Task() {
        }

        public Task(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            count++;
            System.out.println("当前线程是：" + Thread.currentThread() + " 名称：" + name + " 运行结果：" + count);
        }
    }

    static class HrThreadFactory implements ThreadFactory {

        private final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        HrThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
            namePrefix = "hr-pool-" + poolNumber.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        }
    }

}
